# -*- coding: utf-8 -*-
"""
author     : LiGe
date       : 2019-02-16 15:35
description: 
"""

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

db_mysql_connectionString = "mysql+pymysql://root:123456@127.0.0.1/pick_stock?charset=utf8"


class Mysql(object):
    def __init__(self):
        self.__engine = create_engine(db_mysql_connectionString, encoding='utf8', echo=False)
        self.__mySession = sessionmaker(bind=self.__engine)
        self.session = self.__mySession()


class RegionCodeDao(Mysql):
    def insertRegionCode(self, regionCodes=None):
        try:
            if self.queryRegionCodeIsExistByCode(regionCodes[0]) > 0:
                return
            self.session.execute("INSERT INTO `region-code`(`code`, `parentCode`, `name`) VALUES ('%s','%s','%s')" % (
                regionCodes[0], regionCodes[1], regionCodes[2]))
            self.session.commit()
        except Exception as e:
            print(e)
            self.session.rollback()

    def queryRegionCodeIsExistByCode(self, code=None):
        try:
            return self.session.execute("SELECT COUNT(1) FROM `region-code` WHERE `code`='%s'" % code).fetchone()[0]
        except Exception as e:
            print(e)
            return 0

    def queryRegionCodeList(self, code=None):
        try:
            return self.session.execute(
                "SELECT `code` FROM `region-code` WHERE parentCode='%s' ORDER BY id ASC" % code).fetchall()
        except Exception as e:
            print(e)
            return []
